const { exec } = require('child_process');
const os = require('os');
const readline = require('readline');
const path = require('path');
const { spawn } = require('child_process');

// 创建命令行交互接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function detectJava17(callback) {
  exec('java -version', (error, stdout, stderr) => {
    if (error) {
      console.error('Java 未安装或未配置到系统 PATH。');
      return callback(false, null);
    }

    const versionStr = stderr.match(/version\s"([^"]+)"/);
    if (!versionStr) {
      console.error('无法解析 Java 版本。');
      return callback(false, null);
    }

    const version = versionStr[1];
    if (version.startsWith('17')) {
      console.log(`✅ 检测到 Java 17: ${version}`);
      return callback(true, version);
    } else {
      console.warn(`⚠️ 当前 Java 版本为 ${version}，不是 Java 17。`);
      rl.question('是否强制运行？(y/N): ', (answer) => {
        rl.close();
        if (answer.trim().toLowerCase() === 'y') {
          callback(true, version);
        } else {
          callback(false, version);
        }
      });
    }
  });
}

function runSpringBoot() {
  const mvnCommand = os.platform() === 'win32' ? 'mvn.cmd' : 'mvn';
  const command = `${mvnCommand} spring-boot:run`;

  console.log(`🚀 正在运行命令: ${command}`);

  const child = exec(command);

  child.stdout.on('data', (data) => {
    process.stdout.write(data);
  });

  child.stderr.on('data', (data) => {
    process.stderr.write(data);
  });

  child.on('close', (code) => {
    console.log(`🔚 Maven 命令执行结束，退出码: ${code}`);
  });
}

// 运行 install-hanlp.js 脚本
function runInstallHanlp(callback) {
  console.log('🔧 正在初始化 HanLP 环境...');
  
  const installScriptPath = path.join(__dirname, 'install-hanlp.js');
  const nodeCommand = process.execPath;
  
  const child = spawn(nodeCommand, [installScriptPath], {
    cwd: process.cwd(),
    stdio: 'inherit'
  });

  child.on('close', (code) => {
    if (code === 0) {
      console.log('✅ HanLP 环境初始化完成');
      callback(true);
    } else {
      console.error(`❌ HanLP 环境初始化失败，退出码: ${code}`);
      callback(false);
    }
  });

  child.on('error', (error) => {
    console.error('❌ 运行 install-hanlp.js 脚本时出错:', error.message);
    callback(false);
  });
}

// 主流程
runInstallHanlp((success) => {
  if (success) {
    detectJava17((shouldRun, version) => {
      if (shouldRun) {
        runSpringBoot();
      } else {
        console.log('取消运行。请安装 Java 17 以获得最佳支持。');
        process.exit(0);
      }
    });
  } else {
    console.log('❌ HanLP 环境初始化失败，终止运行。');
    process.exit(1);
  }
});